<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends CommonController {
    public function index(){
        
        $result = session('?ID_CARD');
        if(!empty($result)){

            $this->redirect('Database/index');
        }else{

            $this->redirect('Index/login');
        }
    }

    /*
     * 登录页面
     */
    public function login() {
        if(!IS_POST){

            $this->display();
        }else{

            $email = I('post.email');
            if(!empty($email)){

                $map['email'] = trim($email);
            }
            
            $password = I('post.password');
            if(!empty($password)){

                $map['password'] = md5(trim($password));
            }

            $DB_member = M('member');
            $result = $DB_member->where($map)->find();

            if($result){

                $login_time = I('server.REQUEST_TIME');
                $ID_CARD = md5($map['username']).md5($map['password']).md5($login_time);

                session('ID_CARD',$ID_CARD);

                session('mid',$result['mid']);

                $this->success('登录成功!',U('Home/Database/index'),3);
            }else{

                $this->error('用户名不存在!','',1);
            }
        }
        
    }


    /**
     * 注册页面
     */
    public function register(){

        if(!IS_POST){

            $this->display();
        }else{

            $username = I('post.username');
            if(!empty($username)){

                $data['username'] = $username;
            }

            $email = I('post.email');
            if(!empty($email)){

                $data['email'] = $email;
            }

            $password_one = trim(I('post.password_one'));
            $password_two = trim(I('post.password_two'));
            if(empty($password_one) || empty($password_two)){

                $this->error('密码不能为空!','',1);
            }else{

                if($password_one != $password_two){

                    $this->error('两次密码不相同,请重新输入','',3);
                }else{

                    $data['password'] = md5($password_one);
                    $data['password_raw'] = $password_two;
                }
            }

            $data['ctime'] = I('server.REQUEST_TIME');

            $DB_member = M('member');

            $result = $DB_member->data($data)->add();

            if($result){

                $this->success('注册成功,请登录!',U('Home/Index/login'),3);
            }else{

                $this->error('注册失败,请重试!','',1);
            }
        }
        
    }
    
    
    /*
     * 主界面，登录之后才可以看到
     */
    public function dashboard() {
        
        /*
         * ************** 需要增加 登录的判断
         */
        $this->display();
    }
    
    
    /*
     * 空页面
     */
    public function _empty() {
        $this->display("empty");
    }
}
